import {
  asyncRouterMap,
  constantRouterMap
} from '@/router'
import {
  getModule,
  setModule
} from '@/utils/auth'
import lazyLoading from '@/utils/lazyLoading'
import req from '@/utils/req'
import Layout from '@/views/Layout/index'
// import moudle from '@/views/system/moudle'
import router from '@/router'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

function generaMenu(routers, data) {

  data.forEach((item) => {
    let cpm = null;
    if (!item.ParentCode) {
      cpm = Layout;
    }else{
      if (item.MUrl) {
        cpm = lazyLoading(item.MUrl);
      }
    }
    let menu = {
      path: item.MUrl,
      component: cpm,
      hidden: true,
      children: [],
      name: item.MUrl,
      meta: {
        title: item.MName,
        icon: item.MIcon,
        id:  item.ID.toString()
      }
    }
    if (item.Childrens) {
      generaMenu(menu.children, item.Childrens)
    }
    routers.push(menu)
  })
}
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
      router.addRoutes(state.routers)
    },
    Delete_SET_ROUTERS: (state, routers) => {
      state.addRouters = [];
    }
  },
  actions: {
    GenerateRoutes({
      commit
    }, data) {
      return new Promise(resolve => {
        if (getModule()) {
          let menu = JSON.parse(getModule())
          let routers = []
          generaMenu(routers, menu)
          console.log(routers)
          commit('SET_ROUTERS', routers)
          resolve()
        } else {
          req.get('System/GetSysModule', {}).then(res => {
            if (res.StatusCode === 200) {
              // 设置缓存
              setModule(JSON.stringify(res.Data))
              let routers = []
              generaMenu(routers, res.Data)
              commit('SET_ROUTERS', routers)
              resolve()
            } else {
              resolve()
            }
          })
        }
      })
    },
    ClearAllADDROUTERS({commit},data){
      commit('Delete_SET_ROUTERS', null)
    }
  }
}

export default permission
